package org.fire.service;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.fire.exception.MinaConnectionException;
import org.fire.mina.MinaConnectorHandler;
import org.fire.mina.MinaProtocolCodecFactory;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MinaService extends Service {

//	private static final String TAG = "MinaService";

	private IoSession session;

	// public void MyMethod() {
	// Log.i(TAG, "BindService-->MyMethod()");
	// }

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	public void doConnectToServer() throws MinaConnectionException {
		try {
			NioSocketConnector connector = new NioSocketConnector();
			connector.getFilterChain().addLast("codec",
					new ProtocolCodecFilter(new MinaProtocolCodecFactory()));

			connector.setConnectTimeoutCheckInterval(30);
			connector.setHandler(new MinaConnectorHandler());

			ConnectFuture cf = connector.connect(new InetSocketAddress(
					"192.168.1.109", 9123));
			cf.awaitUninterruptibly(30000);

			session = cf.getSession();
			session.setAttribute("application", this);

			sendMessage("{\"addr\":\"00000001\", \"action\":\"login\"}");

		} catch (Exception e) {
			throw new MinaConnectionException(e);
		}
	}

	public void sendMessage(String str) throws MinaConnectionException {
		session.write(str);
	}
}